package com.ry.quartz.config;

import java.io.IOException;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

@Configuration
public class QuartzConfig {

	@Autowired
	private JobFactory jobFactory;

	@Resource(name = "slaveDataSource")
	private DataSource slaveDataSource;
	
	@Bean
	public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
		// 获取配置属性
		PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
		propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
		// 在quartz.properties中的属性被读取并注入后再初始化对象
		propertiesFactoryBean.afterPropertiesSet();
		// 创建SchedulerFactoryBean
		SchedulerFactoryBean factory = new SchedulerFactoryBean();
		factory.setQuartzProperties(propertiesFactoryBean.getObject());
		factory.setJobFactory(jobFactory);
		factory.setDataSource(slaveDataSource);
		factory.setApplicationContextSchedulerContextKey("applicationContextKey");
		return factory;
	}

	/*
	 * 通过SchedulerFactoryBean获取Scheduler的实例
	 */
	@Bean
	public Scheduler scheduler() throws IOException {
		return schedulerFactoryBean().getScheduler();
	}

}
